//
//  BecomeRoomChiefViewController.m
//  Fangmm
//
//  Created by 阮琦 on 16/3/12.
//  Copyright © 2016年 com.fangmm. All rights reserved.
//

#import "BecomeRoomChiefViewController.h"
#import "CheckSelfMessageViewController.h"
#import "WebViewController.h"

#import "HouseTitleTableViewCell.h"
#import "ChooseRoomTableViewCell.h"

#import <SDWebImage/UIImageView+WebCache.h>
#import <SDWebImage/UIButton+WebCache.h>

#import <TSMessages/TSMessageView.h>

#import "ACMacros.h"
#import "HttpServer.h"

@interface BecomeRoomChiefViewController () <UITableViewDataSource, UITableViewDelegate, ChooseRoomCellDelegate>

@end

@implementation BecomeRoomChiefViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self insertBackground];
    [self configureTableView];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    self.navigationController.navigationBarHidden = true;
}

- (void)viewWillDisappear:(BOOL)animated {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    self.navigationController.navigationBarHidden = false;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - Configuring the view’s layout behavior
- (void)insertBackground {
    UIImageView *backgroundImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Height)];
    [backgroundImageView setImage:[UIImage imageNamed:@"screen_bg"]];
    [self.view insertSubview:backgroundImageView atIndex:0];
}

- (void)configureTableView {
    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];
    [self.tableView setBackgroundColor:[UIColor clearColor]];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.tableView registerNib:[UINib nibWithNibName:@"HouseTitleTableViewCell" bundle:nil] forCellReuseIdentifier:@"HouseTitleTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ChooseRoomTableViewCell" bundle:nil] forCellReuseIdentifier:@"ChooseRoomTableViewCell"];
    
    UITapGestureRecognizer *cancelTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cancelInput)];
    [self.tableView addGestureRecognizer:cancelTap];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 1;
            break;
        case 1:
            return 1;
            break;
            
        default:
            return 0;
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    switch (section) {
        case 0:
        {
            HouseTitleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HouseTitleTableViewCell"];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            cell.topLine.hidden = true;
            [cell setBackgroundColor:[UIColor clearColor]];
            [cell.housePriceLabel setText:[NSString stringWithFormat:@"¥%d /整租",self.house.rent]];
            [cell.housePriceLabel setFont:[UIFont systemFontOfSize:12]];
            [cell.houseMessage sd_setImageWithURL:[NSURL URLWithString:self.house.cover]];
            [cell.houseNameLabel setText:self.house.community];
            [cell.houseAreaLabel setText:self.house.region];
            [cell.houseNumLabel setText:[NSString stringWithFormat:@" %d室%d厅%d卫",self.house.roomNum, self.house.hallNum, self.house.toiletNum]];
            [cell.houseAreaLabel setText:[NSString stringWithFormat:@" %dm²", self.house.area]];
            NSArray *array = @[cell.housePriceLabel, cell.houseNameLabel, cell.houseNumLabel, cell.houseAreaLabel, cell.houseRegionLabel, cell.roomChiefNumLabel];
            
            for (UILabel *label in array) {
                [label setTextColor:[UIColor whiteColor]];
            }
            return cell;
        }
            break;
        case 1:
        {
            ChooseRoomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChooseRoomTableViewCell"];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            [cell setDelegate:self];
            cell.houseCount = self.house.roomNum;
            if (self.house.roomNum >= 3) {
                cell.houseCount = 3;
            }
            cell.wholeRent = self.house.rent;
            NSArray *buttons = @[cell.aRoomChooseButton, cell.bRoomChooseButton, cell.cRoomChooseButton];
            for (int i = 0; i < cell.houseCount; i++) {
                [buttons[i] setHidden:false];
            }
            [cell setBackgroundColor:[UIColor clearColor]];
            return cell;
        }
            break;
        default:
            return cell;
            break;
    }

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    switch (section) {
        case 0:
            return 130;
            break;
        case 1:
            return 200;
            break;
        default:
            return 0;
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 10;
            break;
            
        default:
            return 30;
            break;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *header = [[UIView alloc]init];
    [header setBackgroundColor:[UIColor clearColor]];
    if (section == 1) {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, Main_Screen_Width, 30)];
        [label setTextColor:[UIColor whiteColor]];
        [label setText:@"请先选择您的房间,整租请全部选择(多选)"];
        [label setFont:[UIFont systemFontOfSize:10]];
        [header addSubview:label];
    }
    return header;
}

#pragma mark - Triggering Methods
- (IBAction)clickToCancelPop:(UIButton *)sender {
    [self dismissViewControllerAnimated:true completion:^{
        
    }];
}

- (IBAction)clickToCommit:(UIButton *)sender {
    ChooseRoomTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
    if (cell.firstLineView.hidden && cell.secondLineView.hidden) {
        if ([cell.minePriceLabel.text isEqualToString:@"0"]) {
            [TSMessage showNotificationInViewController:self title:@"还没有选择房间!" subtitle:@"" type:TSMessageNotificationTypeWarning duration:2.0 canBeDismissedByUser:true];
        } else {
            [self wholeRentRequest];
        }
    } else if (cell.firstLineView.hidden == false && cell.secondLineView.hidden) {
        NSString *roomName;
        NSInteger roomPrice;
        if ([cell.firstRoomLabel.text isEqualToString:@"RoomA"]) {
            roomName = [self.house.rooms[0] objectForKey:@"name"];
            roomPrice = cell.firstLineRent;
        } else if ([cell.firstRoomLabel.text isEqualToString:@"RoomB"]) {
            roomName = [self.house.rooms[1] objectForKey:@"name"];
            roomPrice = cell.firstLineRent;
        } else if ([cell.firstRoomLabel.text isEqualToString:@"RoomC"]) {
            roomName = [self.house.rooms[2] objectForKey:@"name"];
            roomPrice = cell.firstLineRent;
        }
        NSString *offer = [NSString stringWithFormat:@"%@|%ld",roomName, (long)roomPrice];
        if (cell.firstPriceTextfield.text == nil || [cell.firstPriceTextfield.text isEqual:@""]) {
            [TSMessage showNotificationInViewController:self title:@"您还没有填写房间报价!" subtitle:@"" type:TSMessageNotificationTypeWarning duration:2.0 canBeDismissedByUser:true];
        } else {
            [self presentCheckSelfWithOffer:offer];
        }
    } else if (cell.firstLineView.hidden == false && cell.secondLineView.hidden == false) {
        NSString *offer = @"";
        if ([cell.firstRoomLabel.text isEqualToString:@"RoomA"] && [cell.secondRoomLabel.text isEqualToString:@"RoomB"])
        {
            offer = [NSString stringWithFormat:@"%@|%ld,%@|%ld",[self.house.rooms[0] objectForKey:@"name"], (long)cell.firstLineRent,[self.house.rooms[1] objectForKey:@"name"], (long)cell.secondLineRent];
        } else if ([cell.firstRoomLabel.text isEqualToString:@"RoomA"] && [cell.secondRoomLabel.text isEqualToString:@"RoomC"])
        {
            offer = [NSString stringWithFormat:@"%@|%ld,%@|%ld",[self.house.rooms[0] objectForKey:@"name"], (long)cell.firstLineRent,[self.house.rooms[2] objectForKey:@"name"], (long)cell.secondLineRent];
        } else if ([cell.firstRoomLabel.text isEqualToString:@"RoomB"] && [cell.secondRoomLabel.text isEqualToString:@"RoomC"])
        {
            offer = [NSString stringWithFormat:@"%@|%ld,%@|%ld",[self.house.rooms[1] objectForKey:@"name"], (long)cell.firstLineRent,[self.house.rooms[2] objectForKey:@"name"], (long)cell.secondLineRent];
        }
        if (cell.firstPriceTextfield.text == nil || [cell.firstPriceTextfield.text isEqual:@""] || cell.secondPriceTextfield.text == nil || [cell.secondPriceTextfield.text isEqual:@""]) {
            [TSMessage showNotificationInViewController:self title:@"您还没有填写房间报价!" subtitle:@"" type:TSMessageNotificationTypeWarning duration:2.0 canBeDismissedByUser:true];
        } else {
            [self presentCheckSelfWithOffer:offer];
        }
    }
}

#pragma mark - Network methods
- (void)wholeRentRequest {
    [HttpServer postToCreateTeamWithHouseId:self.house.houseId AndOffers:@"" WithSuccessBlock:^(NSDictionary *successDic) {
        [self dismissViewControllerAnimated:true completion:^{
            
        }];
    } withFailBlock:^(id failData) {
        NSLog(@"%@",failData);
        [TSMessage showNotificationInViewController:self title:@"请求出错!" subtitle:@"请稍后重试" type:TSMessageNotificationTypeError duration:2.0 canBeDismissedByUser:true];
    }];
}

- (void)presentCheckSelfWithOffer:(NSString *)offer {
    [HttpServer postToCreateTeamWithHouseId:self.house.houseId AndOffers:offer WithSuccessBlock:^(NSDictionary *successDic) {
        NSString *successTeamId = [successDic objectForKey:@"teamId"];
        CheckSelfMessageViewController *checkSelfMessageVC = [[CheckSelfMessageViewController alloc]initWithNibName:@"CheckSelfMessageViewController" bundle:nil];
        checkSelfMessageVC.passingType = @"create";
        checkSelfMessageVC.passingTeamId = successTeamId;
        [self.navigationController pushViewController:checkSelfMessageVC animated:true];
    } withFailBlock:^(id failData) {
        NSLog(@"%@",failData);
        if ([[failData allKeys] containsObject:@"msg"]) {
            NSString *string = [failData objectForKey:@"msg"];
            [TSMessage showNotificationInViewController:self title:@"创建小组失败!" subtitle:string type:TSMessageNotificationTypeError duration:2.0 canBeDismissedByUser:true];
        } else {
            [TSMessage showNotificationInViewController:self title:@"创建小组失败!" subtitle:@"" type:TSMessageNotificationTypeError duration:2.0 canBeDismissedByUser:true];
        }
    }];
}

- (IBAction)chiefIntroButtonClicked:(UIButton *)sender {
    WebViewController *webVC = [[WebViewController alloc]init];
    webVC.destinationUrl = @"http://m.fangmm.com/app/client/about/chief";
    webVC.titleString = @"室长介绍";
    [self.navigationController pushViewController:webVC animated:true];
}

- (void)textFieldBeginEditing {
    [self.tableView setContentOffset:CGPointMake(0, 120)];
}

- (void)textFieldEndEditing {
    [self.tableView setContentOffset:CGPointMake(0, 0)];
}

- (void)alertWithTitle:(NSString *)title andSubTitle:(NSString *)subTitle {
    [TSMessage showNotificationInViewController:self title:title subtitle:subTitle type:TSMessageNotificationTypeError duration:2.0 canBeDismissedByUser:true];
}

- (void)cancelInput {
    ChooseRoomTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
    [cell.firstPriceTextfield resignFirstResponder];
    [cell.secondPriceTextfield resignFirstResponder];
}
@end
